<template>
  <!-- 其他费用 -->
  <div class="work-voucher-info">
    <el-button
      v-if="!readonly"
      @click="handleAdd"
      type="text"
      icon="el-icon-plus"
      >{{ $t('新增') }}</el-button
    >
    <el-table :data="tableData">
      <el-table-column
        v-for="item in cols"
        :key="item.listColumnName"
        :label="item.tableColumnName"
        :prop="item.listColumnName"
      >
        <template slot-scope="{ row, $index }">
          <template v-if="item.listColumnName === 'amountType'">
            {{ getObj(amountTypeOpts)[row[item.listColumnName]] }}
          </template>
          <template v-else-if="item.listColumnName === 'taxRate'">
            {{ row[item.listColumnName] ? row[item.listColumnName] + '%' : '' }}
          </template>
          <template v-else-if="item.listColumnName === 'paymentMethod'">
            {{ getObj(paymentMethodOpts)[row[item.listColumnName]] }}
          </template>
          <template v-else-if="item.listColumnName === 'paymentTime'">
            <template v-if="row.paymentTime">
              {{ paymentTimeObj[row.paymentTime.payTime] }}
              {{
                row.paymentTime.dayCount
                  ? $t('{slot1}个自然日', { slot1: row.paymentTime.dayCount })
                  : ''
              }}
            </template>
          </template>
          <template v-else>
            {{ row[item.listColumnName] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" width="100" v-if="!readonly">
        <template slot-scope="{ row, $index }">
          <el-button type="text" @click="handleEdit($index, row)">{{
            $t('修改')
          }}</el-button>
          <el-button type="text" @click="handleDel($index)">{{
            $t('删除')
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-if="dialogVisible"
      :title="title"
      :visible.sync="dialogVisible"
      width="100%"
      custom-class="add-parameter-dialog"
      @close="handleClose"
    >
      <div class="dialog-content">
        <el-form
          :model="formData"
          ref="formData"
          label-width="170px"
          label-position="top"
          :rules="rules"
        >
          <el-row>
            <el-form-item :label="$t('费用项：')" prop="expenseItemNumber">
              <el-select
                v-model="formData.expenseItemNumber"
                @change="changeExpenseItem"
              >
                <el-option
                  v-for="(item, index) in feeOpts"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item :label="$t('金额类型：')" prop="amountType">
              <el-select
                v-model="formData.amountType"
                @change="changeAmountType"
              >
                <el-option
                  v-for="(item, index) in amountTypeOpts"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item :label="$t('税率：')" prop="taxRate">
              <el-input v-model="formData.taxRate">
                <span slot="append">%</span>
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              :label="$t('费用金额：')"
              prop="costAmount"
              :rules="
                formData.amountType == 1
                  ? rules.costAmount
                  : { required: false }
              "
            >
              <el-input
                v-model="formData.costAmount"
                :disabled="formData.amountType != 1"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item :label="$t('支付方式：')" prop="paymentMethod">
              <el-select
                v-model="formData.paymentMethod"
                @change="changePaymentMethod"
              >
                <el-option
                  v-for="(item, index) in paymentMethodOpts"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              :label="$t('付款周期（月1付）：')"
              prop="paymentCycle"
              :rules="
                formData.paymentMethod == 2
                  ? rules.paymentCycle
                  : { required: false }
              "
            >
              <el-input
                v-model="formData.paymentCycle"
                :disabled="formData.paymentMethod != 2"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('付款时间：')" prop="payTime">
                <el-select v-model="formData.payTime">
                  <el-option
                    v-for="(item, index) in paymentTimeOpts"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" prop="dayCount" label-width="0px">
                <el-input v-model="formData.dayCount">
                  <span slot="append">{{ $t('个自然日') }}</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">{{ $t('取消') }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{
          $t('确定')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import nonStandardService from '@/services/nonStandardService'
import eventBus from '@/assets/utils/eventBus.js'
export default {
  name: 'otherExpenses',
  props: {
    detail: {
      type: Object,
      default: () => {
        return {}
      },
    },
    value: {},
    disabled: Boolean,
    parameter: {
      type: Object,
      default: () => {
        return {}
      },
    },
    definitionId: {},
    rows: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      formData: {},
      tableData: [],
      readonly: false,
      cols: [],
      title: this.$t('添加其他费用'),
      dialogVisible: false,
      currentIndex: null,
      currentRow: {},
      rules: {
        expenseItemNumber: [
          {
            required: true,
            message: this.$t('请选择费用项'),
            trigger: 'change',
          },
        ],

        amountType: [
          {
            required: true,
            message: this.$t('请选择金额类型'),
            trigger: 'change',
          },
        ],

        taxRate: [
          { required: true, validator: this.isTaxRate, trigger: 'blur' },
        ],

        costAmount: [
          { required: true, validator: this.isCostAmount, trigger: 'blur' },
        ],

        paymentMethod: [
          {
            required: true,
            message: this.$t('请选择支付方式'),
            trigger: 'change',
          },
        ],

        paymentCycle: [
          { required: true, validator: this.isPaymentCycle, trigger: 'blur' },
        ],

        dayCount: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(this.$t('请输入')))
                return
              } else if (value && !/^(0|[1-9][0-9]{0,1})$/.test(value)) {
                callback(new Error(this.$t('最大支持2位整数')))
                return
              } else {
                callback()
                return
              }
            },
            trigger: 'blur',
          },
        ],
      },
      feeOpts: [],
      amountTypeOpts: [
        { value: 1, label: this.$t('固定金额') },
        { value: 2, label: this.$t('变动金额') },
      ],

      paymentMethodOpts: [
        { value: 1, label: this.$t('一次性支付') },
        { value: 2, label: this.$t('分期支付') },
      ],

      paymentTimeOpts: [{ value: 1, label: this.$t('计费周期开始前') }],

      paymentTimeObj: {
        1: this.$t('计费周期开始前'),
        2: this.$t('计费周期结束后'),
      },
      startTime: null,
      endTime: null,
      rateObj: {},
      operType: null,
    }
  },
  created() {
    this.readonly = Boolean(this.$route.query.readonly)
    this.getCols()
    if (this.value) {
      this.setData()
    } else {
      this.$emit('input', this.tableData)
    }
    eventBus.$on('startEndTimeChange', (val) => {
      if (val) {
        this.startTime = val[0]
        this.endTime = val[1]
      } else {
        this.startTime = null
        this.endTime = null
      }
    })
    this.getRowsData()
    this.getlListFeeItem()
  },
  methods: {
    getlListFeeItem() {
      nonStandardService.listFeeItem({}).then((res) => {
        if (res.code == 200) {
          this.feeOpts = (res.data || []).map((it) => {
            return {
              ...it,
              value: it.costCode,
              label:
                it.costCode && it.costName
                  ? it.costCode + '-' + it.costName
                  : '',
            }
          })
        }
      })
    },
    getCols() {
      nonStandardService.queryParkCostColumnList({}).then((res) => {
        if (res.code == 200) {
          this.cols = res.data.data || []
        }
      })
    },
    getObj(data) {
      let obj = {}
      data.forEach((it) => {
        obj[it.value] = it.label
      })
      return obj
    },
    getRowsData() {
      ;(this.rows || []).forEach((item) => {
        ;(item || []).forEach((it) => {
          if (it.parameterNumber === 'rate') {
            this.rateObj = it
          }
        })
      })
    },
    getMonthDiff() {
      let diff = 0
      if (this.startTime && this.endTime) {
        // 解析日期字符串为Date对象
        const startDate = new Date(this.startTime)
        const endDate = new Date(this.endTime)
        // 获取年份和月份的差异
        let yearDiff = endDate.getFullYear() - startDate.getFullYear()
        let monthDiff = endDate.getMonth() - startDate.getMonth()
        // 如果结束月份小于开始月份，则需要从年份差异中减去1年，并加上12个月（因为每个月有30天左右的差异）
        if (monthDiff < 0) {
          yearDiff--
          monthDiff += 12
        }
        // 根据结束期限日是否晚于开始期限日设置X的值
        let x = endDate.getDate() > startDate.getDate() ? 1 : 0
        diff = yearDiff * 12 + monthDiff + x
      }
      return diff
    },
    // 和抬头里面的税率小数位数保持一致
    isTaxRate(rule, value, callback) {
      const parameterValue = this.rateObj.parameterValueStr
        ? JSON.parse(this.rateObj.parameterValueStr)
        : {}
      let reg = null
      if (parameterValue.decimalLimit || parameterValue.decimalLimit == 0) {
        reg = new RegExp(
          `^(-)*([0-9]{1,${parameterValue.integerLimit}})(\\.[0-9]{0,${parameterValue.decimalLimit}})?$`
        )
      } else {
        reg = new RegExp(
          `^(-)*([0-9]{1,${parameterValue.integerLimit}})(\\.[0-9]{0,8})?$`
        )
      }
      let maxValue = parameterValue.maxValue ? parameterValue.maxValue : null
      let minValue = parameterValue.minValue ? parameterValue.minValue : null
      let decimalLimit =
        parameterValue.decimalLimit || parameterValue.decimalLimit == 0
          ? parameterValue.decimalLimit
          : 8
      if (!value) {
        callback(new Error(this.$t('请输入税率')))
      } else if (!reg.test(value)) {
        callback(
          new Error(
            this.$t('只能输入整数最多') +
              parameterValue.integerLimit +
              this.$t('位,小数') +
              decimalLimit +
              this.$t('位')
          )
        )
      } else if (
        (maxValue && Number(value) > maxValue) ||
        (minValue && Number(value) < minValue)
      ) {
        if (maxValue && Number(value) > maxValue) {
          callback(
            new Error(this.$t('请输入比') + maxValue + this.$t('小的值'))
          )
        }
        if (minValue && Number(value) < minValue) {
          callback(
            new Error(this.$t('请输入比') + minValue + this.$t('大的值'))
          )
        }
      } else {
        callback()
      }
    },
    isCostAmount(rule, value, callback) {
      let reg = /^\d{1,13}(\.\d{1,2})?$/
      if (!value) {
        callback(new Error(this.$t('请输入费用金额')))
      } else if (!reg.test(value)) {
        this.$set(this.formData, 'costAmount', '')
        callback(new Error(this.$t('限13位数字+2位小数')))
      } else if (value == 0) {
        this.$set(this.formData, 'costAmount', '')
        callback(new Error(this.$t('必须正数')))
      } else {
        callback()
      }
    },
    isPaymentCycle(rule, value, callback) {
      if (!value) {
        callback(new Error(this.$t('请输入付款周期')))
      } else if (!/^\d+$/.test(value)) {
        callback(new Error(this.$t('请输入整数')))
      } else if (value && Number(value) > this.getMonthDiff()) {
        callback(new Error(this.$t('付款周期需小于有效期限')))
        return
      } else {
        callback()
      }
    },
    changeExpenseItem(val) {
      let info = this.feeOpts.find((it) => it.value === val) || {}
      this.$set(this.formData, 'expenseItem', info.label)
      this.$set(
        this.formData,
        'taxRate',
        info.taxRate ? info.taxRate * 100 : null
      )
    },
    changeAmountType(val) {
      if (+val === 1) {
        this.paymentTimeOpts = [
          { value: 1, label: this.$t('计费周期开始前') },
          { value: 2, label: this.$t('计费周期结束后') },
        ]
      } else {
        this.$set(this.formData, 'costAmount', '')
        this.paymentTimeOpts = [{ value: 2, label: this.$t('计费周期结束后') }]

        this.$set(this.formData, 'payTime', 2)
      }
    },
    changePaymentMethod(val) {
      if (+val !== 2) {
        this.$set(this.formData, 'paymentCycle', '')
      }
    },
    // 新增
    handleAdd() {
      if (this.tableData.length > 9) {
        this.$message.warning(this.$t('最多只能添加10条数据'))
        return
      }
      this.title = this.$t('添加其他费用')
      this.operType = 1
      this.formData = {
        payTime: 1,
      }
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(index, row) {
      this.currentIndex = index
      this.formData = {
        ...row,
        ...row.paymentTime,
      }
      this.title = this.$t('编辑其他费用')
      this.operType = 2
      this.dialogVisible = true
    },
    // 删除
    handleDel(index) {
      this.tableData.splice(index, 1)
    },
    handleClose() {
      this.dialogVisible = false
    },
    handleConfirm() {
      this.$refs.formData.validate().then((res) => {
        let params = {
          ...this.formData,
          paymentTime: {
            payTime: this.formData.payTime,
            dayCount: this.formData.dayCount,
          },
        }
        delete params.payTime
        delete params.dayCount
        if (this.operType == 1) {
          this.tableData.push(params)
        } else if (this.operType == 2) {
          this.$set(this.tableData, this.currentIndex, params)
        }
        this.handleClose()
      })
    },
    setData() {
      if (this.value && JSON.parse(this.value).length) {
        this.tableData = JSON.parse(this.value)
      } else {
        this.tableData = []
      }
      this.$emit('input', this.tableData)
    },
    getData() {
      return this.tableData
    },
    // validator() {
    //     return this.$refs.formData.validate();
    // },
  },
}
</script>
<style lang="scss" scoped>
.work-voucher-info {
  width: 100%;

  .work-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    width: 95%;
    min-width: 460px;
    background: #fff;
    padding: 20px;
    box-sizing: border-box;

    .work-item {
      width: 90%;

      .work-upload-files {
        margin-top: 12px;
        display: flex;
        flex-wrap: wrap;

        .file {
          margin-right: 10px;
          cursor: pointer;
        }

        .el-icon-close {
          cursor: pointer;
          margin-left: 24px;
        }
      }
    }
  }
}
</style>
